package com.cse210.grocerwe.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.cse210.grocerwe.common.*;
import com.cse210.grocerwe.client.*;
import org.restlet.resource.Put;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

/**
 * The server side implementation of the Restlet resource.
 */
public class APIResourceA extends ServerResource implements
        APIInterfaceA {
    PersistenceManager pm;
    /*
     * (non-Javadoc)
     * @see restlet.common.ShoppingResource#createList(java.lang.String, restlet.common.SGroup)
     * Non prototype methods
     */
    
    @Post
    public SItem[] getAllItems()
    {
    	pm = PMF.get().getPersistenceManager();
    	String user = (String) getRequest().getAttributes().get("user");
    	boolean first = true;
    	Query q0 = pm.newQuery(MapUserToGroup.class);
    	q0.setFilter("user == x");
    	q0.declareParameters("String x");
	    @SuppressWarnings("unchecked")
    	List<MapUserToGroup> mugs = (List<MapUserToGroup>) q0.execute(user);
	    
    	String filter = "global_list == false &&";
    	for(MapUserToGroup mug : mugs)
    	{
    		if(first)
    		{
    			first = false;
    			filter+="(group == "+mug.getGroup();
    		}
    		else
    		{
    			filter+=" || group == "+mug.getGroup();
    		}
    	}
    	filter+=")";
    	Query q = pm.newQuery(ShoppingItem.class);
    	q.setFilter(filter);
    	q.declareParameters("String x");
	    @SuppressWarnings("unchecked")
		List<ShoppingItem> inventory = (List<ShoppingItem>) q.execute(user);
	    SItem[] sInventory = new SItem[inventory.size()];
		
	    for( int i = 0; i < inventory.size();i++ )
	    {
	    	ShoppingItem si = inventory.get(i);
	    	sInventory[i] = si.toSItem();
	    }
	    
	    pm.close();
	    return sInventory;
    }

    // The specific item/group fields should be added front-end
    @Put
    public void addItem(SItem item)
    {
    	pm  = PMF.get().getPersistenceManager();
    	ShoppingItem si = new ShoppingItem(item);
        try {
            pm.makePersistent(si);
        } finally {
            pm.close();
        }
    }  
}

